package bold.module.zk;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;

/**
 * @author khaiLoon
 * @date 2018/10/16
 **/
public class Main {

    private final static String zk_url = "172.16.26.30:2181";
//    private final static String zk_url = "127.0.0.1:2181";

    public static void main1(String[] args) throws IOException, InterruptedException {
        //初始化zk
        ZooKeeper zooKeeper = new ZooKeeper(zk_url, 5000, new Watcher() {
            public void process(WatchedEvent watchedEvent) {
                Event.KeeperState state = watchedEvent.getState();
                Event.EventType type = watchedEvent.getType();
                if (Event.KeeperState.SyncConnected == state) {
                    if (Event.EventType.None == type) {
                        System.out.println(1111);
                    }
                }
            }
        });


        try {
            //创建持久化节点
            zooKeeper.create("/gang", "你好".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            //获取节点数据
            byte[] data = zooKeeper.getData("/gang", false, null);
            System.out.println(new String(data));
            //修改节点数据
            zooKeeper.setData("/gang", "吕金刚".getBytes(), 0);
            //删除节点数据
            zooKeeper.delete("/gang", -1);
            //创建临时节点 异步创建
            zooKeeper.create("/jingang", "临时节点".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, new AsyncCallback.StringCallback() {
                @Override
                public void processResult(int i, String s, Object o, String s1) {
                    System.out.println(o);
                    System.out.println(i);
                    System.out.println(s1);
                    System.out.println(s);
                }
            }, "a");
            //获取临时节点数据
            byte[] jingangs = zooKeeper.getData("/jingang", false, null);
            System.out.println(new String(jingangs));
            //验证节点是否存在
            Stat exists = zooKeeper.exists("/jingang", false);
            System.out.println(exists);
        } catch (KeeperException | InterruptedException e) {
            e.printStackTrace();
        }
        zooKeeper.close();
    }

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        ZooKeeper zooKeeper = new ZooKeeper(zk_url, 5000, new Watcher() {
            public void process(WatchedEvent watchedEvent) {
                Event.KeeperState state = watchedEvent.getState();
                Event.EventType type = watchedEvent.getType();
                System.out.println("state:" + state + "  type:" + type);
            }
        });

        //持久化节点
        zooKeeper.create("/gang", "你好".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
    }

}
